package com.example.icampusevent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.icampusevent.jsonobjects.ReturnStatus;
import com.google.gson.Gson;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private String userId;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // Disable the built-in main action bar
        getActionBar().setDisplayShowHomeEnabled(false);
        getActionBar().setDisplayShowTitleEnabled(false);
        
        ListView loginListView = (ListView)findViewById(R.id.login_list);
        loginListView.setAdapter(new LoginListViewAdapter(this));
        
        Button signupButton = (Button)findViewById(R.id.gosignup_button);
        signupButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
	    		startActivity(intent);
			}
        });
        
        Button loginButton = (Button)findViewById(R.id.login_button);
        loginButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				login();
			}
        });
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	ListView signupListView = (ListView)findViewById(R.id.login_list);
    	
    	// Check preference
    	try {
    		File file = getBaseContext().getFileStreamPath("USERID");
    		if(file.exists()) {
    			FileInputStream fis = openFileInput("USERID");
        		byte[] buffer = new byte[100];
        		int length = fis.read(buffer);
        		if(length != 0) {
        			userId = new String(buffer, 0, length, "UTF-8");
            		Intent intent = new Intent(this, MainActivity.class);
            		intent.putExtra("USERID", userId);
            		startActivity(intent);
        		}
    		}
    	} catch(IOException e) {
    		toast(e.getMessage());
    	}
    }
    
    private void login() {
    	ListView signupListView = (ListView)findViewById(R.id.login_list);
    	userId = ((EditText)signupListView.getItemAtPosition(0)).getText().toString();
    	String pwd = ((EditText)signupListView.getItemAtPosition(1)).getText().toString();
    	
    	String url = "http://hamedaan.usc.edu:8080/team15/UserServlet?q=login&userid=" + userId +
    			"&password=" + pwd;
    	LoginTask task = new LoginTask();
    	task.execute(url);
    }
    
    private class LoginTask extends AsyncTask<String, Integer, Reader> {
	     protected Reader doInBackground(String... url) {
	    	 InputStream source = retrieveStream(url[0]);
	 		 if(source == null) return null;
	 		 
	 		 Reader inputReader = new InputStreamReader(source);
	 		 return inputReader;
	     }

	     protected void onPostExecute(Reader json) {
	 		 Gson gson = new Gson();
			 ReturnStatus status = gson.fromJson(json, ReturnStatus.class);
			 if(status.getStatus().toLowerCase().equals("success")) {
				 
				 try {
					 // write user id to internal storage
					 FileOutputStream fos = openFileOutput("USERID", Context.MODE_PRIVATE);
					 fos.write(userId.getBytes());
					 fos.close();

					 Intent intent = new Intent(LoginActivity.this, MainActivity.class);
					 intent.putExtra("USERID", userId);
					 startActivity(intent);
				 } catch(IOException e) { 
					 toast("Cannot recode user ID");
				 }
				 
			 }
			 else if(status.getStatus().toLowerCase().equals("wrong password")) {
				 toast("Wrong Password.");
			 }
			 else if(status.getStatus().toLowerCase().equals("not exist")) {
				 toast("User ID not exists.");
			 }
			 else {
				 toast("Error happens.");
			 }
	     }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		
	 		return null;
	 	}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }
    
    public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(this, text, duration);
		toast.show();
	}
}
